import { defineStore } from 'pinia'

export const useMainStore = defineStore('main', {
  state: () => ({
    toolbar: {
      visible: false,
      enter: true
    },
    sortInfo: [],
    currentUser: {},
    currentAdmin: {},
    webInfo: {
      webName: "",
      webTitle: [],
      notices: [],
      footer: "",
      backgroundImage: "",
      avatar: ""
    },
    dynamicWallpapers: [],
    playlist: 526887854,
    fonts: [],
    // Emoji data will be loaded on-demand and strictly controlled
    emojiLoaded: false,
    emojiMap: new Map(),
    emojiCategories: [],
    currentWallpaper: undefined,
    showPosterVideo: false,
    isMuted: true
  }),
  
  getters: {
    articleTotal: (state) => {
      if (state.sortInfo !== null && state.sortInfo.length !== 0) {
        if (state.sortInfo.length === 1) {
          return state.sortInfo[0].countOfSort;
        } else {
          return state.sortInfo.reduce((prev, curr) => {
            if (typeof prev === "number") {
              return prev + curr.countOfSort;
            } else {
              return prev.countOfSort + curr.countOfSort;
            }
          });
        }
      } else {
        return 0;
      }
    },
    
    navigationBar: (state) => {
      if (state.sortInfo !== null && state.sortInfo.length !== 0) {
        return state.sortInfo.filter(f => {
          return f.sortType === 0;
        }).sort((s1, s2) => {
          return s1.priority - s2.priority;
        })
      } else {
        return [];
      }
    },
    
    hasEmojiLoaded: (state) => {
      return state.emojiLoaded;
    },
    
    getEmojiCategories: (state) => {
      return state.emojiCategories;
    },
    
    getEmojiByText: (state) => (text) => {
      return state.emojiMap.get(text);
    }
  },
  
  actions: {
    setShowPosterVideo(value) {
      this.showPosterVideo = value;
    },
    
    setIsMuted(value) {
      this.isMuted = value;
    },
    
    changeCurrentWallpaper(wallpaper) {
      console.log(wallpaper);
      this.currentWallpaper = wallpaper;
    },
    
    pushPlaylist(playlist) {
      this.playlist = playlist;
    },
    
    changePlaylist(playlist) {
      this.playlist = playlist;
    },
    
    changeToolbarStatus(toolbarState) {
      this.toolbar = toolbarState;
    },
    
    loadSortInfo(sortInfo) {
      this.sortInfo = sortInfo;
    },
    
    loadCurrentUser(user) {
      this.currentUser = user;
    },
    
    loadCurrentAdmin(user) {
      this.currentAdmin = user;
    },
    
    loadWebInfo(webInfo) {
      webInfo.webTitle = webInfo.webTitle.split('');
      webInfo.notices = JSON.parse(webInfo.notices);
      this.webInfo = webInfo;
    },
    
    /**
     * 清除emoji数据，用于重置状态
     */
    clearEmojiData() {
      this.emojiLoaded = false;
      this.emojiMap.clear();
      this.emojiCategories = [];
    },
    
    /**
     * 从本地JSON文件加载emoji数据
     */
    async loadLocalEmojiData() {
      if (this.emojiLoaded) return;
      
      try {
        // 动态导入emoji.json
        const emojiModule = await import('../assets/json/emoji.json');
        this.processEmojiData(emojiModule.default);
        console.log('成功加载本地emoji数据');
      } catch (error) {
        console.error('加载本地emoji数据失败:', error);
      }
    },
    
    /**
     * 加载已经存储在localStorage中的emoji数据
     */
    loadStoredEmojiData() {
      if (this.emojiLoaded) return;
      
      try {
        const storedEmoji = localStorage.getItem('emoji');
        if (storedEmoji) {
          const emojiData = JSON.parse(storedEmoji);
          this.processEmojiData(emojiData);
          console.log('成功从localStorage加载emoji数据');
          return true;
        }
      } catch (error) {
        console.error('从localStorage加载emoji数据失败:', error);
      }
      return false;
    },
    
    /**
     * 处理emoji数据，填充map和categories
     */
    processEmojiData(emojiData) {
      if (!Array.isArray(emojiData) || this.emojiLoaded) return;
      
      // 清空现有数据
      this.emojiMap.clear();
      this.emojiCategories = [];
      
      // 复制分类数据
      this.emojiCategories = emojiData.map(category => ({
        text: category.text,
        url: category.url
      }));
      
      // 填充表情映射
      emojiData.forEach(category => {
        if (category.emote && Array.isArray(category.emote)) {
          category.emote.forEach(emote => {
            if (emote.text && emote.url && !this.emojiMap.has(emote.text)) {
              // 记录该表情所属的分类，方便后续按分类获取
              const emoteWithCategory = {
                ...emote,
                category: category.text
              };
              this.emojiMap.set(emote.text, emoteWithCategory);
            }
          });
        }
      });
      
      // 标记为已加载
      this.emojiLoaded = true;
      
      // 保存到localStorage，保持原结构
      localStorage.setItem('emoji', JSON.stringify(emojiData));
    },
    
    /**
     * 合并API提供的emoji数据
     */
    mergeApiEmojiData(apiEmojiData) {
      if (!Array.isArray(apiEmojiData)) return;
      
      // 如果本地没有emoji数据，先加载本地数据
      if (!this.emojiLoaded) {
        this.loadStoredEmojiData();
      }
      
      // 收集当前已有的分类名
      const existingCategories = new Set(this.emojiCategories.map(cat => cat.text));
      
      // 处理所有API数据（不仅是新分类，保证所有网络数据都被处理）
      apiEmojiData.forEach(category => {
        // 如果是新分类，添加到分类列表
        if (!existingCategories.has(category.text)) {
          this.emojiCategories.push({
            text: category.text,
            url: category.url
          });
        }
        
        // 无论是否新分类，都添加该分类中的所有表情
        if (category.emote && Array.isArray(category.emote)) {
          category.emote.forEach(emote => {
            if (emote.text && emote.url) {
              // 记录该表情所属的分类
              const emoteWithCategory = {
                ...emote,
                category: category.text
              };
              // 即使重复也更新，确保网络数据优先
              this.emojiMap.set(emote.text, emoteWithCategory);
            }
          });
        }
      });
      
      // 构建完整的emoji数据以保存到localStorage
      const fullEmojiData = [];
      
      // 从emojiMap恢复完整的数据结构
      const categoryEmotes = {};
      
      // 初始化每个分类的表情数组
      this.emojiCategories.forEach(cat => {
        categoryEmotes[cat.text] = [];
      });
      
      // 将每个表情放入对应的分类
      this.emojiMap.forEach(emote => {
        const catName = emote.category;
        if (catName && categoryEmotes[catName]) {
          categoryEmotes[catName].push(emote);
        }
      });
      
      // 构建完整数据
      this.emojiCategories.forEach(cat => {
        fullEmojiData.push({
          text: cat.text,
          url: cat.url,
          emote: categoryEmotes[cat.text] || []
        });
      });
      
      // 保存更新后的完整数据到localStorage
      localStorage.setItem('emoji', JSON.stringify(fullEmojiData));
    },
    
    /**
     * 获取特定分类的表情
     */
    getEmotesByCategory(categoryText) {
      if (!this.emojiLoaded) return [];
      
      const result = [];
      
      // 遍历所有emoji找出属于该分类的
      this.emojiMap.forEach((emote, text) => {
        // 通过分类名关联
        if (emote.category === categoryText) {
          result.push(emote);
        }
      });
      
      return result;
    },
    
    /**
     * 获取完整的emoji数据
     */
    getFullEmojiData() {
      if (!this.emojiLoaded) return [];
      
      const result = [];
      
      // 为每个分类创建完整数据
      for (const category of this.emojiCategories) {
        const emotes = this.getEmotesByCategory(category.text);
        result.push({
          text: category.text,
          url: category.url,
          emote: emotes
        });
      }
      
      return result;
    }
  },
  
  persist: {
    storage: localStorage,
    paths: ['toolbar', 'currentUser', 'currentAdmin', 'webInfo', 'currentWallpaper', 'showPosterVideo', 'isMuted']
  }
})
